import React, { useEffect, useState, Component, useRef } from 'react';
import { fetchSync, request } from '@/utils/request';
import { history, Link } from 'umi';
import { connect, router } from 'dva';

import enUS from 'antd/es/locale/en_US';
import {
    Menu, Switch, Divider, Checkbox, Button, Row, Col, Tooltip, notification, Skeleton, Avatar, FloatButton, DatePicker, Upload, TimePicker,
    Form, Modal, Select, Tree, Icon, Radio, Table, Tag, Pagination, Input, Space, message, Card, Tabs, Collapse, Image, ConfigProvider
} from 'antd';
import {
    MailOutlined, AppstoreOutlined, SettingOutlined, AudioOutlined, UserOutlined, PlusOutlined, EditOutlined,
    CloseCircleOutlined, ArrowRightOutlined, RollbackOutlined, CloseOutlined, RightOutlined,CrownOutlined
} from '@ant-design/icons';

import 'mapbox-gl/dist/mapbox-gl.css';
import styles from './user.less';
import ItemActivity from './itemActivity';
import { getByParam, getUserId, getUserName } from '@/utils/loginAssert';
import moment from 'moment';

let markers = [];
let jiuyuanMarkers = [];

const layout = {
    labelCol: {
        span: 6,
    },
    wrapperCol: {
        span: 4,
    },
};
export default (props) => {
    const [map, setMap] = useState(null);
    const [isUserModal, setIsUserModal] = useState(false);
    const showmapContainer = useRef(null);
    const echarts8 = useRef(null);
    const commentList = useRef(null);

    const [fileList, setFileList] = useState([])
    const [isInitActivities, setIsInitActivities] = useState(false)
    const [activities, setActivities] = useState([])

    const [dataInitiated, setdataInitiated] = useState([])
    const [dataParticipated, setdataParticipated] = useState([])

    //初始函数
    useEffect(async () => {
        //此处编写 组件挂载之后和组件重新渲染之后执行的代码
        // qu_data = await fetchSync('/api/fangxun/qu/findAll')
        initActivities()
        console.log(getByParam('follows'))
        return () => {
            //此处编写 组件即将被卸载前执行的代码
        }
        // 4、若传值，但是传的是空数组 []，则表示该useEffect里的内容仅会在“挂载完成后和组件即将被卸载前”执行一次；
    }, [])

    const initActivities = () => {
        request('/api/joy/activity/findAll', {
            method: 'get'
        }).then(res => {
            console.log(res)
            if (res.success) {
                //  sort by time desc
                // let data = res.data.sort((a,b)=>  moment(b.activityTime) - moment(a.activityTime)) 
                // setActivities(res.data)
                // setdataInitiated
                let data1 = res.data.filter(item => item.userId == getUserId())
                setdataInitiated(data1 || [])

                let data2 = res.data.filter(item => (item.userId != getUserId()) && (item.userNames) && (item.userNames.indexOf(getUserName()) != -1))
                setdataParticipated(data2 || [])
            }
        })
    }

    const handleInitActivitiesCancel = () => {
        setIsInitActivities(false);
    };
    const onFinishInitActivities = (values) => {
        let userName = getUserName()
        let userId = getUserId()
        console.log(values)
        const { name, address, content, routes, activityTime, activityDate, activityType, list } = values;
        if (!list){
            message.warning('please upload image !')
            return;
        }
        request('/api/joy/activity/save', {
            method: 'POST',
            data: {
                userId,
                userName,
                name,
                address,
                routes: routes.replace(/\s+/g, ''),
                activityTime: activityDate.format('YYYY-MM-DD') + 'T' + activityTime.format('hh:mm:ss') + '.000Z',
                content,
                base64Images: list.fileList.map(it => it.thumbUrl),
                activityType,
                userNames: [userName]
            }
        }).then(res => {
            console.log(res);
            if (res.success) {
                message.success('success！')
                // refreshList()
                setIsInitActivities(false);
                initActivities()
            }
        })
    }

    // 上传
    const getBase64 = (file) =>
        new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = (error) => reject(error);
        });
    const uploadProps = {
        onRemove: (file) => {
            const index = fileList.indexOf(file);
            const newFileList = fileList.slice();
            newFileList.splice(index, 1);
            setFileList(newFileList);
        },
        beforeUpload: (file) => {
            const isJpgOrPng = true || file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/gif';
            if (!isJpgOrPng) {
                message.error('请上传图片文件 格式 JPG/PNG/JPG/GIF !');
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                message.error('图片大小不超过 2MB!');
            }
            if (isJpgOrPng && isLt2M) {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = e => {
                    file.originFileObj = file
                    file.thumbUrl = e.target.result;
                    let flag = 0;
                    fileList.forEach((item, index) => {
                        if (file.name === item.name) {
                            message.error("文件已存在!");
                            flag = 1;
                        }
                    })
                    if (!flag) {
                        setFileList([...fileList, file])
                    }
                    return false;
                };
            } else {
                return false;
            }
        },
        fileList,
    };
    const handlePreview = async (file) => {
        console.log(file)
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }

        let images = []
        if (file.url) {
            images.push(file.url)
        } else {
            images.push(file.preview)
        }
        // setPreviewImages(images);
        // setPreviewVisible(true);
        // setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1));
    };
    const uploadButton = (
        <div>
            <PlusOutlined />
            <div
                style={{
                    marginTop: 8,
                }}
            >
                Upload
            </div>
        </div>
    );

    const onFinishEditUser = (values) => {
        let userName = getUserName()
        let userId = getUserId()
        console.log(values)
        const { username, list, password, phoneNum } = values;
        let data = {
            id: userId,
            username,
            password,
            phoneNum,
        }
        if (list) {
            data.avatarImg = list.fileList[0].thumbUrl
        }
        request('/api/user/update', {
            method: 'POST',
            data 
        }).then(res => {
            console.log(res);
            if (res.success) {
                message.success('success！')
                setIsUserModal(false);
                sessionStorage.setItem("user", JSON.stringify(data));
                window.location.reload()
            }
        })
    }

    return (
        <div className={styles.container}>

            <div className={styles.header}>
                <Avatar
                    size={80}
                    src={
                        <Image
                            src={getByParam('avatarImg') || require('./img/head1.png')}
                            style={{
                                width: 100,
                            }}
                        />
                    }
                />
                <div className={styles.userInfo}>
                    <label> {getUserName()} { (moment(getByParam('vipDueDate')) - new Date() > 0) ?  <CrownOutlined style={{fontSize: 30, color:'gold'}} /> :'' }</label>
                    <span> ID: {100681191 + ~~(Math.random() * 100)} </span>
                    <Tooltip title="edit user">
                        <Button type="dashed" shape="circle" icon={<EditOutlined />} onClick={() => setIsUserModal(true)} />
                    </Tooltip>
                </div>
                <Tooltip placement="bottom" title={'quit app'}>
                    <Button style={{ position: 'absolute', right: 20 }} onClick={() => history.push('/user/login')} type='dashed' icon={<CloseOutlined />} />
                </Tooltip>
            </div>
            <br />

            <div className={styles.joinvip}>
                <span>VIP CENTER</span>
                <Link to="./vip">
                    <Button type="link" style={{ marginTop: 12 }} shape="circle" icon={<RightOutlined style={{ color: '#c2b04d', fontSize: 32 }} />} />
                </Link>
            </div>
            <Tabs items={[
                {
                    label: `My Follows`,
                    key: '1',
                    children: <>
                        {
                            getByParam('follows')?.map((it, key) => {
                                // return <Tag key={key} icon={<UserOutlined />} closeIcon={<CloseCircleOutlined />} color="#108ee9" onClose={()=>closeUser(it)}>{it}</Tag>
                                return <Tag key={key} icon={<UserOutlined />} color="#108ee9" >{it}</Tag>
                            })
                        }
                    </>
                },
            ]} />

            <Tabs tabBarExtraContent={ (moment(getByParam('vipDueDate')) - new Date() > 0) ? <Button onClick={() => setIsInitActivities(true)}>Publish an activity</Button> :''} items={[
                {
                    label: `Initiated`,
                    key: '1',
                    children: <ItemActivity data={dataInitiated} />,
                },
                {
                    label: `Participated`,
                    key: '2',
                    children: <ItemActivity data={dataParticipated} />,
                },
            ]} />


            <Modal title="Initiate activities" open={isInitActivities} onCancel={handleInitActivitiesCancel} footer={null}>
                <Form {...layout} name="nest-messages" onFinish={onFinishInitActivities}
                    initialValues={{
                        name: 'Cycling Rally 2024',
                        address: 'Shang Hai',
                        activityDate: moment('2024-05-01'),
                        // activityTime: moment('11:00:00'),
                        routes: `[
                            104.05264534135353,
                            30.706596598195773
                          ],
                          [
                            104.04998721563135,
                            30.705014358095298
                          ],
                          [
                            104.04829504010456,
                            30.70403832731519
                          ],
                          [
                            104.04761111916332,
                            30.70488705029274
                          ],
                          [
                            104.04837259814946,
                            30.70537809374926
                          ],
                          [
                            104.04850656204519,
                            30.706839084806504
                          ]`,
                        content: 'Cycling Rally 2024 Cycling Rally 2024 Cycling Rally 2024 Cycling Rally 2024 Cycling Rally 2024 Cycling Rally 2024 Cycling Rally 2024 Cycling Rally 2024 Cycling Rally 2024',
                    }}
                >
                    <Form.Item label="activity name" name="name" rules={[
                        {
                            required: true,
                            message: 'Please input activity name',
                        },
                    ]}>
                        <Input />
                    </Form.Item>
                    <Form.Item label="activity address" name="address" rules={[
                        {
                            required: true,
                            message: 'Please input activity address',
                        },
                    ]}>
                        <Input />
                    </Form.Item>
                    <Form.Item label="activity date" name="activityDate" rules={[
                        {
                            required: true,
                            message: 'Please input activity date',
                        },
                    ]}>
                        <DatePicker />
                    </Form.Item>
                    <Form.Item label="activity time" name="activityTime" rules={[
                        {
                            required: true,
                            message: 'Please input activity time',
                        },
                    ]}>
                        <TimePicker />
                    </Form.Item>
                    <Form.Item label="activity type" name="activityType" rules={[
                        {
                            required: true,
                            message: 'Please input activity type',
                        },
                    ]}>
                        <Select>
                            <Select.Option value={'Running'}>Running</Select.Option>
                            <Select.Option value={'Cycling'}>Cycling</Select.Option>
                            <Select.Option value={'SelfDriving'}>Self Driving</Select.Option>
                        </Select>
                    </Form.Item>
                    <Form.Item label="activity routes" name="routes" rules={[
                        {
                            required: true,
                            message: 'Please input activity routes',
                        },
                    ]}>
                        <Input.TextArea
                            autoSize={{ minRows: 4, maxRows: 8 }}
                        />
                    </Form.Item>
                    <Form.Item label="activity content" name="content" rules={[
                        {
                            required: true,
                            message: 'Please input activity content',
                        },
                    ]}>
                        <Input.TextArea
                            autoSize={{ minRows: 4, maxRows: 8 }}
                        />
                    </Form.Item>
                    <Form.Item label="activity photoes" name="list">
                        <Upload
                            listType="picture-card"
                            fileList={fileList}
                            preview={false}
                            headers={{ 'content-type': 'multipart/form-data' }}
                            onPreview={handlePreview}
                            {...uploadProps}
                        >
                            {fileList.length >= 9 ? null : uploadButton}
                        </Upload>
                    </Form.Item>
                    <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 20 }}>
                        <Button type="primary" htmlType="submit">
                            ok
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>

            <Modal title="Edit User" open={isUserModal} onCancel={() => setIsUserModal(false)} footer={null}>
                <Form {...layout} name="nest-messages" onFinish={onFinishEditUser}
                    initialValues={{
                        username: getUserName(),
                        password: getByParam('password'),
                        phoneNum: getByParam('phoneNum'),
                    }}
                >
                    <Form.Item label="username" name="username">
                        <Input />
                    </Form.Item>
                    <Form.Item label="password" name="password" >
                        <Input.Password />
                    </Form.Item>
                    <Form.Item label="phone number" name="phoneNum" >
                        <Input />
                    </Form.Item>
                    <Form.Item label="avatarImg" name="list">
                        <Upload
                            listType="picture-card"
                            fileList={fileList}
                            preview={false}
                            headers={{ 'content-type': 'multipart/form-data' }}
                            onPreview={handlePreview}
                            {...uploadProps}
                        >
                            {fileList.length >= 1 ? null : uploadButton}
                        </Upload>
                    </Form.Item>
                    <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 20 }}>
                        <Button type="primary" htmlType="submit">
                            ok
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
}
